<template>
    <div class="IndexView">
      <div class="IndexView_con">
        <ul class="menu_tab">
          <li v-for="(v) in MenuData" :class="{ current: v.current }" :key="v.type" @click="clickMenu(v)">
            {{ v.txt }}
          </li>
        </ul>
        
        <!-- 表单部分 -->
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm"
        @keyup.enter.native="submitForm(ruleFormRef)">
  
          <el-form-item prop="username">
            <label>用户名</label>
            <el-input v-model="ruleForm.username" type="text" autocomplete="off" minlength="5" maxlength="15" />
          </el-form-item>
  
          <el-form-item prop="password">
            <label>密码</label>
            <el-input v-model="ruleForm.password" type="password" autocomplete="off" minlength="8" maxlength="15" />
          </el-form-item>
  
          <el-form-item prop="repassword" v-show="model === 'register'">
            <label>重复密码</label>
            <el-input v-model="ruleForm.repassword" type="password" autocomplete="off" minlength="8"
              maxlength="15" />
          </el-form-item>
  
          <el-form-item prop="mailbox" v-show="model === 'register'">
            <label>邮箱</label>
            <el-input v-model="ruleForm.mailbox" type="email" autocomplete="off" minlength="8" maxlength="30" />
          </el-form-item>
  
          <el-form-item>
            <el-button :disabled="btnbool" type="primary" class="IndexView_btn block" @click="submitForm(ruleFormRef)">
              {{ model === "login" ? "登录" : "注册" }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-icon><Loading /></el-icon>
      </div>
    </div>
  </template>
  
  
  <script lang="ts" setup>
  import { reactive, ref, onMounted, watch, h } from 'vue'
  //创建复杂数据类型
  import { FormInstance, FormRules, ElMessage } from 'element-plus'
  import { useRouter } from "vue-router";
  
  // 自定义工具包
  import * as ck from "../../utils/verfifaction.js"
  import Link from "../../api/Link.js";
  import apiurl from "../../api/url.js";
  import { tr } from 'element-plus/es/locale';
  import Usemd5 from "../../hook/index.js";
  import { Loading  } from "@element-plus/icons-vue";
import { composeEventHandlers } from 'element-plus/es/utils';
  
  
  const MenuData = reactive([
    { txt: "登录", current: true, type: "login" },
    { txt: "注册", current: false, type: "register" },
  ])
  
  let model = ref("login")
  
  let router = useRouter()
  
  onMounted(() => {
    console.log(process.env.VUE_APP_API)
  })
  
  let clickMenu = (item: any) => {
    MenuData.forEach((elemt) => {
      elemt.current = false
    })
    item.current = true;
    // 修改保存点击的状态
    model.value = item.type;
  }
  
  
  // elementplus表单部分
  const ruleFormRef = ref<FormInstance>()
  
  const validatename = (rule: any, value: any, callback: any) => {
    if (!value) {
      return callback(new Error('用户名不能为空'))
    } else if (ck.verifyName(value)) {
      return callback(new Error('用户名格式错误! 用户名应为6-12个字符'))
    }
    else {
      callback()
    }
  }
  const validatePass = (rule: any, value: any, callback: any) => {
  
    if (!value) {
      return callback(new Error('密码不能为空！'))
    } else if (ck.verifyPasswd(value)) {
      return callback(new Error('密码格式错误! 密码 至少8个字符,至少1个大写字母,1个小写字母和1个数字,不能包含特殊字符（非数字字母'))
    }
    else {
      callback()
    }
  }
  const validatePass2 = (rule: any, value: any, callback: any) => {
    // 因为登录没有重复密码的校验，所以登录页面时取消重复密码的校验
    if (model.value === "login") {
      callback()
    }
  
    if (!value) {
      return callback(new Error('重复密码不能为空！'))
    } else if (value !== ruleForm.password) {
      return callback(new Error('两次密码不相同！'))
    }
    else {
      callback()
    }
  }
  const validatemailbox = (rule: any, value: any, callback: any) => {
    if (model.value === "login") {
      callback()
    }
  
    if (!value) {
      return callback(new Error('邮箱不能为空！'))
    } else if
      (ck.verifyEmile(value)) {
      callback(new Error('邮箱格式错误！'))
    } else {
      callback()
    }
  }
  
  const ruleForm = reactive({
    username: '',
    password: '',
    repassword: '',
    mailbox: '',
  })
  
  //判断当前页面输入框是否有值
  let btnbool = ref(true)
  watch(ruleForm, (newval, oldval) => {
    if (model.value === "login") {
      if (newval.username != "" && newval.password != "") {
        btnbool.value = false
      } else {
        btnbool.value = true
      }
    } else {
      if (newval.username != "" && newval.password != "" && newval.repassword != "") {
        btnbool.value = false
      } else {
        btnbool.value = true
      }
    }
  })

  let btn = ref(false)
  const change = (btn:any) =>{
    if (btn) {
      console.log("已经启动");
    }else{
      btn.value = !btn.value
    }   
  }

  
  //设置触发方式，失去焦点触发
  const rules = reactive<FormRules<typeof ruleForm>>({
    username: [{ validator: validatename, trigger: 'blur' }],
    password: [{ validator: validatePass, trigger: 'blur' }],
    repassword: [{ validator: validatePass2, trigger: 'blur' }],
    mailbox: [{ validator: validatemailbox, trigger: 'blur' }],
  })

  const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: any) => {
      if (valid) {
        console.log('submit!')
        //登录操作
        if (model.value === "login") {
          console.log("登录")
          
          Link(apiurl.register, "GET", {}, { username: ruleForm.username, password: Usemd5(ruleForm.password).value }).then((ok: any) => {
            console.log(ok)
            if (ok.data.length != 0) {
              console.log("登录成功")
              ElMessage({
                message: '登录成功',
                type: 'success',
              })
              //页面跳转
                router.push("/home")

            } else {
              console.log("登录失败")
              ElMessage({
                message: h('p', null, [
                  h('span', null, '登录失败'),
                  h('i', { style: 'color: teal' }, '请重试！'),
                ]),
              })
            }
          })
  
        } else {
          let data = {
            username: ruleForm.username,
            password: Usemd5(ruleForm.password).value,
            mailbox: ruleForm.mailbox
          }
          Link(apiurl.register, "POST", data).then((ok: any) => {
            console.log(ok);

            
            if (Object.keys(ok.data).length !== 0) {
              ElMessage({
                message: '注册成功！',
                type: 'success',
              })
              model.value = "login",
                MenuData.forEach(v => {
                  v.current = false
                })
              MenuData[0].current = true
            } else {
              ElMessage.error('注册失败！')
            }
          })
        }
  
  
      } else {
        console.log('error submit!')
        return false
      }
    })
  }
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  </script>
   
  
  <style lang="scss">
  .IndexView {
    height: 100%;
  }
  
  html,
  body,
  #app {
    height: 100%;
  }
  
  .menu_tab {
    text-align: right;
  
    li {
      display: inline-block;
      width: 88px;
      line-height: 36px;
      font-size: 14px;
      color: rgb(0, 3, 8);
      border-radius: 2px;
      cursor: pointer;
      text-align: center;
    }
  }
  
  .current {
    background-color:rgb(203, 199, 199);
    
  }
  
  .demo-ruleForm {
    width: 30%;
    margin: 50px auto;
  
    label {
      display: block;
      margin-bottom: 3px;
      font-size: 14px;
      color: #271818;
    }
  
    .block {
      display: block;
      width: 100%;
    }
  
    .IndexView_btn {
      margin-top: 20px;
    }
  }

  .demo-ruleForm:last-child {
    margin-bottom:0
  }
  </style>